﻿using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class UnityPlugins : MonoBehaviour
{
    public Image image;
    string imgName;
    private string wx_appId;
    private string wx_appSecret;

    private string xl_appId;
    private string xl_appSecret;

    private NativeAndroid nativeAndroid;
    private NativeiOS nativeiOS;

    private int width = 200;

    // Use this for initialization
    void Start()
    {
        wx_appId = "wx80819d29219b428f";
        wx_appSecret = "cb2ab1dea7ebe003a02bb09d5e90c020";

        xl_appId = "wx80819d29219b428f";
        xl_appSecret = "cb2ab1dea7ebe003a02bb09d5e90c020";

        nativeAndroid = new NativeAndroid();
        nativeiOS = new NativeiOS();

        if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
        {
            nativeAndroid.WxInit(wx_appId);
            nativeiOS.iWxInit(wx_appId);

            //nativeAndroid.XlInit(xl_appId);
            //nativeiOS.iXlInit(xl_appSecret);

            nativeAndroid.GetLaunchInfo(gameObject.name, "OnLaunchInfo");
            nativeiOS.iGetLaunchInfo(gameObject.name, "OnLaunchInfo");
        }
    }

    private void OnGUI()
    {
        if (GUILayout.Button("截屏插入相册", GUILayout.Height(width), GUILayout.Width(width)))
        {
            CaptureCamera();
            Debug.Log("截屏插入相册");
        }

        if (GUILayout.Button("打开相册选照片", GUILayout.Height(width), GUILayout.Width(width)))
        {
#if UNITY_ANDROID
            nativeAndroid.PhotoPick(gameObject.name, "GetPhoto");
#elif UNITY_IOS
            nativeiOS.iPhotoPick(gameObject.name, "GetPhoto");
#endif 
        }

        if (GUILayout.Button("打开相机拍照片", GUILayout.Height(width), GUILayout.Width(width)))
        {
#if UNITY_ANDROID
            nativeAndroid.PhotoTake(gameObject.name, "GetPhoto");
#elif UNITY_IOS
            nativeiOS.iPhotoTake(gameObject.name, "GetPhoto");
#endif 
        }

        if (GUILayout.Button("微信登录", GUILayout.Height(width), GUILayout.Width(width)))
        {
#if UNITY_ANDROID
            nativeAndroid.WxLogin(gameObject.name, "OnWxLogin");
#elif UNITY_IOS
            nativeiOS.iWxLogin(gameObject.name, "OnWxLogin");
#endif 
        }

        if (GUILayout.Button("分享文字到微信", GUILayout.Height(width), GUILayout.Width(width)))
        {
#if UNITY_ANDROID
            nativeAndroid.WxShareText("地狱为王分享文字到微信的测试", 0);
#elif UNITY_IOS
            nativeiOS.iWxShareText("地狱为王分享文字到微信的测试", 0);
#endif  
        }

        //先截屏插入相册再分享图片
        if (GUILayout.Button("分享图片到微信", GUILayout.Height(width), GUILayout.Width(width)))
        {
#if UNITY_ANDROID
            nativeAndroid.WxShareImg(imgName, 0);
#elif UNITY_IOS
            nativeiOS.iWxShareImg(imgName, 0);
#endif   
        }

        //先截屏插入相册再分享链接
        if (GUILayout.Button("分享链接到微信", GUILayout.Height(width), GUILayout.Width(width)))
        {
#if UNITY_ANDROID
            nativeAndroid.WxShareUrl("https://www.xuefei.net.cn", "地狱为王的博客", "地狱为王的博客", imgName, 0);
#elif UNITY_IOS
            nativeiOS.iWxShareUrl("https://www.xuefei.net.cn", "地狱为王的博客", "地狱为王的博客", imgName, 0);
#endif    
        }
    }


    void CaptureCamera()
    {
        Camera camera = Camera.main;
        imgName = DateTime.Now.ToFileTime().ToString() + ".jpg";

        Rect rect = new Rect(0, 0, Screen.width, Screen.height);

        RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 0);
        Texture2D frame = new Texture2D(Screen.width, Screen.height, TextureFormat.RGBA32, false);

        camera.targetTexture = rt;
        camera.Render();

        RenderTexture.active = rt;
        frame.ReadPixels(rect, 0, 0);
        frame.Apply();

        camera.targetTexture = null;
        RenderTexture.active = null;

        byte[] bytes = frame.EncodeToJPG();

        File.WriteAllBytes(Application.persistentDataPath + "/" + imgName, bytes);
        bytes = null;

#if UNITY_ANDROID
        nativeAndroid.PhotoInsert(imgName);
#elif UNITY_IOS
        nativeiOS.iPhotoInsert(Application.persistentDataPath + "/" + imgName);
#endif
    }

    /// <summary>
    /// 从微信获取的code
    /// </summary>
    /// <param name="code"></param>
    public void OnWxLogin(string code)
    {
        StartCoroutine(GetWxInfo(code));
    }

    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns>
    IEnumerator GetWxInfo(string code)
    {
        string access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wx_appId
            + "&secret=" + wx_appSecret
            + "&code=" + code + "&grant_type=authorization_code";
        WWW www1 = new WWW(access_token_url);
        yield return www1;
        AKInfo ak = new AKInfo();
        try
        {
            Debug.Log("www1.text:" + www1.text);
            JsonUtility.FromJsonOverwrite(www1.text, ak);
            www1.Dispose();
            www1 = null;
        }
        catch (Exception e)
        {
            Debug.LogError(e.ToString());
            yield break;
        }

        //获取个人信息
        string getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + ak.access_token
            + "&openid=" + ak.openid;
        WWW www2 = new WWW(getUserInfo);
        yield return www2;
        WXUserInfo userInfo = new WXUserInfo();
        try
        {
            Debug.Log("www2.text:" + www2.text);
            JsonUtility.FromJsonOverwrite(www2.text, userInfo);
            www2.Dispose();
            www2 = null;
        }
        catch (Exception e)
        {
            Debug.LogError(e.ToString());
            yield break;
        }
    }

    public void GetPhoto(string fileName)
    {
        StartCoroutine(LoadTexture(fileName));
    }

    IEnumerator LoadTexture(string name)
    {
        Debug.Log("name:" + name);
        if (name == "")
        {
            yield break;
        }
        string path = "file:///" + Application.persistentDataPath + "/" + name;
        double startTime = (double)Time.time;
        WWW www = new WWW(path);
        yield return www;
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            Texture2D texture = www.texture;
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            image.sprite = sprite;
            startTime = (double)Time.time - startTime;
            Debug.Log("wwww加载用时：" + startTime);
        }
    }

    /// <summary>
    /// access_token相关信息
    /// </summary>
    [SerializeField]
    public class AKInfo
    {
        public string access_token;
        public string expires_in;
        public string refresh_token;
        public string openid;
        public string scope;
        public string unionid;
    }
}